<template>
  <div class="py-4 container-fluid" :style="{ backgroundColor: '#f0f2f5' }">
    <div class="mb-4">
      <el-button type="info" plain size="large" style="margin-right: 20px;">年份</el-button>

      <template v-for="(year, index) in years" :key="year" sty>
        <!-- 下一年：禁用+tooltip -->
        <el-tooltip v-if="year === currentYear + 1" content="新征程待解锁" placement="top" style="margin-right: 20px;">
          <el-button color="#626aef" :disabled="true" plain size="large">
            {{ year }}
          </el-button>
        </el-tooltip>

        <!-- 可点击的年份按钮 -->
        <el-badge v-else :value="selectedYear === year ? '✓' : ''" class="item" color="green"
          style="margin-right: 20px;">
          <el-button :type="types[index % types.length]" plain size="large"
            :class="{ 'selected': selectedYear === year }" @click="getDataByYear(year)">
            {{ year }}
          </el-button>
        </el-badge>
      </template>
      <el-tooltip content="重新获取所有数据" placement="top" style="margin-right: 20px;">
        <el-button style="margin-right: 20px;" color="#626aef" @click="getData(selectedYear, '2')" plain size="large">
          刷新数据
        </el-button>
      </el-tooltip>
    </div>

    <div class="row mb-5">
      <div class="col-lg-12 position-relative z-index-2">
        <div class="row">
          <div v-for="(item, index) in statisticsData" :key="index"   class="col">
            <mini-statistics-card :title="item.title" :detail="generateDetail(item.diff)" :icon="item.icon" />
          </div>
        </div>
        <div class="row mt-4">
          <div class="col-lg-4 col-md-6 mt-4">
            <!-- <chart-holder-card :title="`项目总数:${projectStatus.title}`" -->
            <!-- :subtitle="generateDetailProjectStatus(projectStatus.subtitle)" :update="projectStatus.update"> -->
            <chart-holder-card :title="`项目总数:${projectStatus.title}`" subtitle="">
              <reports-bar-chart :key="projectStatus" ref="chartCardRef" :chart="{
                labels: projectStatus.chartData.labels,
                datasets: {
                  label: '数量',
                  data: projectStatus.chartData.data,
                },
              }" />
            </chart-holder-card>

          </div>
          <div class="col-lg-4 col-md-6 mt-4">
            <!-- <chart-holder-card :title="pieData.text" :update="pieData.update" -->
            <chart-holder-card :title="pieData.text" update="" color="success">
              <PieChart :key="pieData" :height="cardHeight" :chart-data="pieData.data"></PieChart>
            </chart-holder-card>
          </div>
          <div class="col-lg-4 mt-4">
            <!-- <chart-holder-card title="月度新增项目统计" :subtitle="lineData.text" :update="lineData.update" color="dark"> -->
            <chart-holder-card title="月度新增项目统计" color="dark">
              <reports-line-chart :key="lineData" id="tasks-chart" :chart="lineData" />
            </chart-holder-card>
          </div>
        </div>
      </div>
    </div>

    <div class="row">
      <div class="col-lg-8 col-md-6 mb-md-0 mb-4">
        <el-tabs type="border-card">
          <el-tab-pane label="待收质保项目">
            <timeline-list class="h-100" :title="warrantyCount"   description="临近质保期的项目(标红表示已逾期)">
              <el-table border :row-class-name="tableRowClassName" :data="warrantyListD">
                <el-table-column label="项目名称" show-overflow-tooltip width="220" align="center" prop="projectName" />
                <el-table-column label="阶段" align="center" show-overflow-tooltip width="100" prop="phaseName" />
                <el-table-column label="发起人" align="center" show-overflow-tooltip width="80" prop="createUser" />
                <el-table-column label="付款单位" show-overflow-tooltip width="220" align="center" prop="company" />
                <el-table-column label="结算金额" show-overflow-tooltip width="120" align="center"
                  prop="settlementAmount" />
                <el-table-column label="质保金" show-overflow-tooltip width="120" align="center" prop="warranty" />
                <el-table-column label="周期(月)" align="center" prop="cycle" />
                <el-table-column label="起始日期" show-overflow-tooltip align="center" prop="startDate" width="180">
                  <template #default="scope">
                    <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="截止日期" align="center" prop="endDate" width="180">
                  <template #default="scope">
                    <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="质保到期剩余(天)" align="center" prop="warrantyRemaining" />
                <el-table-column label="质保金实收金额" align="center" prop="receivedAmount" />
                <el-table-column label="操作人" align="center" prop="operator" />
                <el-table-column label="操作" fixed="right" width="150" align="center"
                  class-name="small-padding fixed-width">
                  <template #default="scope">
                    <el-tooltip content="查看项目详细信息" placement="top">
                      <el-button link type="primary" @click="handleView(scope.row)">查看</el-button>
                    </el-tooltip>
                    <el-tooltip content="质保金已收?去处理" placement="top">
                      <el-button link type="primary" @click="handleWarranty(scope.row)">去处理</el-button>
                    </el-tooltip>
                  </template>
                </el-table-column>
              </el-table>
              <pagination :page-sizes="[10]" :autoScroll="false" v-show="warrantyTotal > 0" :total="warrantyTotal"
                v-model:page="warrantyQueryParams.pageNum" v-model:limit="warrantyQueryParams.pageSize" @pagination="getWarrantyProject()" />
            </timeline-list>
          </el-tab-pane>
          <el-tab-pane label="待收款项目">
            <timeline-list class="h-100" :title="waitPaymentCount" description="待收款项目:处于验收或核算环节的项目">
              <el-table :data="waitList" border>
                <el-table-column label="项目名称" show-overflow-tooltip width="220" align="center" prop="projectName" />
                <el-table-column label="阶段" align="center" show-overflow-tooltip width="100" prop="phaseName" />
                <el-table-column label="发起人" align="center" show-overflow-tooltip width="80" prop="createUserName" />
                <el-table-column label="立项日期" align="center" prop="approvalDate" width="120" show-overflow-tooltip>
                  <template #default="scope">
                    <span>{{ parseTime(scope.row.approvalDate, "{y}-{m}-{d}") }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="合同金额" align="center" show-overflow-tooltip width="120" prop="contractAmount" />
                <el-table-column label="结算金额" align="center" show-overflow-tooltip width="120"
                  prop="settlementAmount" />
                <el-table-column label="客户名称" align="center" show-overflow-tooltip width="220" prop="customerName" />
                <el-table-column label="管家婆项目" align="center" prop="housekeeperName" show-overflow-tooltip
                  width="300" />
                <el-table-column label="操作" fixed="right" width="150" align="center"
                  class-name="small-padding fixed-width">
                  <template #default="scope">
                    <el-tooltip content="查看详细信息" placement="top">
                      <el-button link type="primary" @click="handleView(scope.row)">查看</el-button>
                    </el-tooltip>
                    <el-tooltip content="项目有新进展?去处理" placement="top">
                      <el-button link type="primary" @click="handles(scope.row)">去处理</el-button>
                    </el-tooltip>
                  </template>
                </el-table-column>
              </el-table>
              <pagination :page-sizes="[10]" :autoScroll="false" v-show="waitPayeeTotal > 0" :total="waitPayeeTotal"
                v-model:page="waitPayeeQueryParams.pageNum" v-model:limit="waitPayeeQueryParams.pageSize" @pagination="getWaitPayeeProject()" />
            </timeline-list>
          </el-tab-pane>
          <el-tab-pane label="超期项目">
            <timeline-list class="h-100" :title="overTimeCount" description="已超过预计验收日期的项目">
              <el-table :data="overTime" border>
                <el-table-column label="项目名称" show-overflow-tooltip width="220" align="center" prop="projectName" />
                <el-table-column label="阶段" align="center" show-overflow-tooltip width="100" prop="phaseName" />
                <el-table-column label="发起人" align="center" show-overflow-tooltip width="80" prop="createUserName" />
                <el-table-column label="预计验收日期" align="center" prop="acceptTime" width="120" show-overflow-tooltip>
                  <template #default="scope">
                    <span>{{ parseTime(scope.row.acceptTime, "{y}-{m}-{d}") }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="已超期(天)" align="center" prop="overDays" show-overflow-tooltip width="120" />
                <el-table-column label="客户名称" align="center" show-overflow-tooltip width="120" prop="customerName" />
                <el-table-column label="管家婆项目" align="center" prop="housekeeperName" show-overflow-tooltip
                  width="300" />
                <el-table-column label="操作" fixed="right" width="150" align="center"
                  class-name="small-padding fixed-width">
                  <template #default="scope">
                    <el-tooltip content="查看详细信息" placement="top">
                      <el-button link type="primary" @click="handleView(scope.row)">查看</el-button>
                    </el-tooltip>
                    <el-tooltip content="项目有新进展?去处理" placement="top">
                      <el-button link type="primary" @click="handles(scope.row)">去处理</el-button>
                    </el-tooltip>
                  </template>
                </el-table-column>
              </el-table>

              <pagination :page-sizes="[10]" :autoScroll="false" v-show="overTimeTotal > 0" :total="overTimeTotal"
                v-model:page="overTimeQueryParams.pageNum" v-model:limit="overTimeQueryParams.pageSize" @pagination="getOverTotalProject()" />
           
              
            </timeline-list>
          </el-tab-pane>
          <el-tab-pane label="待竣工项目">
            <timeline-list class="h-100" :title="waitComplete" description="实施进行中的项目">
              <el-table :data="implementListD" border>
                <el-table-column label="项目名称" show-overflow-tooltip width="220" align="center" prop="projectName" />
                <el-table-column label="阶段" align="center" show-overflow-tooltip width="100" prop="phaseName" />
                <el-table-column label="发起人" align="center" show-overflow-tooltip width="80" prop="createUserName" />
                <el-table-column label="预计验收日期" align="center" prop="acceptTime" width="120" show-overflow-tooltip>
                  <template #default="scope">
                    <span>{{ parseTime(scope.row.acceptTime, "{y}-{m}-{d}") }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="客户名称" align="center" show-overflow-tooltip width="220" prop="customerName" />
                <el-table-column label="管家婆项目" align="center" prop="housekeeperName" show-overflow-tooltip
                  width="300" />
                <el-table-column label="操作" fixed="right" width="150" align="center"
                  class-name="small-padding fixed-width">
                  <template #default="scope">
                    <el-tooltip content="查看详细信息" placement="top">
                      <el-button link type="primary" @click="handleView(scope.row)">查看</el-button>
                    </el-tooltip>
                    <el-tooltip content="项目有新进展?去处理" placement="top">
                      <el-button link type="primary" @click="handles(scope.row)">去处理</el-button>
                    </el-tooltip>
                  </template>
                </el-table-column>
              </el-table>
              <pagination :page-sizes="[10]" :autoScroll="false" v-show="waitCompeleteTotal > 0" :total="waitCompeleteTotal"
                v-model:page="waitCompeleteQueryParams.pageNum" v-model:limit="waitCompeleteQueryParams.pageSize" @pagination="getWaitCompleteProject()" />
           
            </timeline-list>
          </el-tab-pane>
          <el-tab-pane label="配合项目">
            <timeline-list class="h-100" title="配合项目" description="配合项目">
              <el-table :data="assistList" border>
                <el-table-column label="项目名称" show-overflow-tooltip width="220" align="center" prop="projectName" />
                <el-table-column label="阶段" align="center" show-overflow-tooltip width="100" prop="phaseName" />
                <el-table-column label="发起人" align="center" show-overflow-tooltip width="80" prop="createUserName" />
                <el-table-column label="预计验收日期" align="center" prop="acceptTime" width="120" show-overflow-tooltip>
                  <template #default="scope">
                    <span>{{ parseTime(scope.row.acceptTime, "{y}-{m}-{d}") }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="客户名称" align="center" show-overflow-tooltip width="220" prop="customerName" />
                <el-table-column label="管家婆项目" align="center" prop="housekeeperName" show-overflow-tooltip
                  width="300" />
                <el-table-column label="操作" fixed="right" width="150" align="center"
                  class-name="small-padding fixed-width">
                  <template #default="scope">
                    <el-tooltip content="查看详细信息" placement="top">
                      <el-button link type="primary" @click="handleView(scope.row)">查看</el-button>
                    </el-tooltip>
                    <el-tooltip content="项目有新进展?去处理" placement="top">
                      <el-button link type="primary" @click="handles(scope.row)">去处理</el-button>
                    </el-tooltip>
                  </template>
                </el-table-column>
              </el-table>
              <pagination :page-sizes="[10]" :autoScroll="false" v-show="assistTotal > 0" :total="assistTotal"
                v-model:page="assistParams.pageNum" v-model:limit="assistParams.pageSize" @pagination="getAssistList" />
            </timeline-list>
          </el-tab-pane>
          <el-tab-pane label="年度项目汇总">
            <timeline-list class="h-100" title="年度项目汇总" description="年度项目统计">
              <el-table :data="allProjectYear" border>
                <el-table-column label="项目名称" show-overflow-tooltip width="220" align="center" prop="projectName" />
                <el-table-column label="阶段" align="center" show-overflow-tooltip width="100" prop="phaseName" />
                <el-table-column label="发起人" align="center" show-overflow-tooltip width="80" prop="createUserName" />
                <el-table-column label="预计验收日期" align="center" prop="acceptTime" width="120" show-overflow-tooltip>
                  <template #default="scope">
                    <span>{{ parseTime(scope.row.acceptTime, "{y}-{m}-{d}") }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="客户名称" align="center" show-overflow-tooltip width="220" prop="customerName" />
                <el-table-column label="管家婆项目" align="center" prop="housekeeperName" show-overflow-tooltip
                  width="300" />
                <el-table-column label="操作" fixed="right" width="150" align="center"
                  class-name="small-padding fixed-width">
                  <template #default="scope">
                    <el-tooltip content="查看详细信息" placement="top">
                      <el-button link type="primary" @click="handleView(scope.row)">查看</el-button>
                    </el-tooltip>
                    <el-tooltip content="项目有新进展?去处理" placement="top">
                      <el-button link type="primary" @click="handles(scope.row)">去处理</el-button>
                    </el-tooltip>
                  </template>
                </el-table-column>
              </el-table>
              <pagination :page-sizes="[10]" :autoScroll="false" v-show="total > 0" :total="total"
                v-model:page="yearParams.pageNum" v-model:limit="yearParams.pageSize" @pagination="getYearProject" />
            </timeline-list>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="col-lg-4 col-md-6">
        <!-- <el-carousel height="650px">
          <el-carousel-item> -->
        <el-tabs type="border-card">
          <el-tab-pane label="销售排行榜">
            <timeline-list class="h-100" :title="'销售排行榜'"
              :description="`<i class='fa fa-trophy text-warning' aria-hidden='true'></i><span class='font-weight-bold'>年度TOP</span>`">

              <!-- 动态循环销售榜单 -->
              <timeline-item v-for="(item, index) in salesRank" :key="index" :icon="getRankIcon(index)"
              :date-time="item.subText"  :title="item.text" :class="{ 'pb-1': index === salesRank.length - 1 }" />


            </timeline-list>
          </el-tab-pane>

          <el-tab-pane label="利润排行榜">
            <timeline-list class="h-100" :title="'利润排行榜'"
              :description="`<i class='fa fa-trophy text-warning' aria-hidden='true'></i><span class='font-weight-bold'>年度TOP</span>`">

              <!-- 动态循环销售榜单 -->
              <timeline-item v-for="(item, index) in profitRank" :key="index" :icon="getRankIcon(index)"
              :title="item.text" :class="{ 'pb-1': index === salesRank.length - 1 }" />


            </timeline-list>
          </el-tab-pane>

          <el-tab-pane label="利润率排行榜">
            <timeline-list class="h-100" :title="'利润率排行榜'"
              :description="`<i class='fa fa-trophy text-warning' aria-hidden='true'></i><span class='font-weight-bold'>年度TOP</span>`">

              <!-- 动态循环销售榜单 -->
              <timeline-item v-for="(item, index) in profitRateRank" :key="index" :icon="getRankIcon(index)"
               :title="item.text" :class="{ 'pb-1': index === salesRank.length - 1 }" />


            </timeline-list>
          </el-tab-pane>

        </el-tabs>
        <!-- </el-carousel-item>
        </el-carousel> -->
      </div>
    </div>


    <el-dialog v-model="openView" fullscreen append-to-body>
      <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="项目信息" name="first">
          <projectView :key="'projectView' + form.projectNo" :datas="form" :isView="isView" :column="3" :sizes="'large'"
            :personList="personList" :attachmentList="attachmentList" :payList="payList" :warrantyList="warrantyList"
            :implementList="implementList" :accountingList="accountingList"></projectView>
        </el-tab-pane>
        <el-tab-pane label="正式清单" name="second">
          <mainList v-if="activeName == 'second'" :datas="form"></mainList>
        </el-tab-pane>
        <el-tab-pane label="管家婆出库单" name="third">
          <saleList v-if="activeName == 'third'" :datas="form"></saleList>
        </el-tab-pane>
        <el-tab-pane label="费用汇总" name="four">
          <feeList v-if="activeName == 'four'" :datas="form"></feeList>
        </el-tab-pane>
        <el-tab-pane label="清单对比" name="five">
          <compareMainAndSale v-if="activeName == 'five'" :datas="form"></compareMainAndSale>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="cancel">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>

</template>
<script setup>
import ChartHolderCard from "../components/ChartHolderCard.vue";
import ReportsBarChart from "@/examples/Charts/ReportsBarChart.vue";
import ReportsLineChart from "@/examples/Charts/ReportsLineChart.vue";
import MiniStatisticsCard from "../components/MiniStatisticsCard.vue";
import PieChart from '../components/PieChart.vue'
import ProjectCard from "../components/ProjectCard.vue";
import TimelineList from "@/examples/Cards/TimelineList.vue";
import TimelineItem from "@/examples/Cards/TimelineItem.vue";
import logoXD from "@/assets/img/small-logos/logo-xd.svg";
import logoAtlassian from "@/assets/img/small-logos/logo-atlassian.svg";
import logoSlack from "@/assets/img/small-logos/logo-slack.svg";
import logoSpotify from "@/assets/img/small-logos/logo-spotify.svg";
import logoJira from "@/assets/img/small-logos/logo-jira.svg";
import logoInvision from "@/assets/img/small-logos/logo-invision.svg";
import team1 from "@/assets/img/team-1.jpg";
import team2 from "@/assets/img/team-2.jpg";
import team3 from "@/assets/img/team-3.jpg";
import team4 from "@/assets/img/team-4.jpg";
import { myJoinProject, getFirstPanelByYear, getProjectStatus, getPieData, getLineData } from "@/api/project/project";
import setNavPills from "@/assets/js/nav-pills.js";
import { waitPayment, getWarrantyList, overTimeList, getRank, getImplementDataView, getAllProjectYear ,getAssistList} from "../../api/project/project";
import { getProject, listParticipan, listAccounting, listAttachment, listPay, listWarranty, listImplement } from "@/api/project/project";

import projectView from "../project/projectView.vue";
import mainList from "../project/mainList.vue";
import saleList from "../project/saleList.vue";
import feeList from "../project/fee.vue"
import compareMainAndSale from "../project/compareMainAndSale.vue"
import { useRouter } from 'vue-router';
import { h } from 'vue'
import { ElNotification } from 'element-plus'
import { ref } from "vue";
const router = useRouter();
const open = ref(false);
const isView = ref(false);
const openView = ref(false);
const activeName = ref('first')
const attachmentList = ref([]);
const payList = ref([]);
const personList = ref([]);
const accountingList = ref([]);
const implementList = ref([]);
const warrantyList = ref([]);
function handleClick(item, event) {
  // activeName
  console.log("tabs页面跳转", item.paneName, event)
  activeName.value = item.paneName
}

function cancel() {
  openView.value = false
}

const tableRowClassName = ({ row }) => {
  return row.rowStatus == "1" ? 'gray2-row' : '';
}

//定义数据
const data = reactive({
  form: {
    createUserName: null,
    createUserId: null,
    createDeptName: null,
    createDept: null,
  },
  firstPanel: [
    { text: '项目总金额(万元)', value: 0, diff: 0 },
    { text: '结算总金额(万元)', value: 0, diff: 0 },
    { text: '开票总金额(万元)', value: 0, diff: 0 },
    { text: '收款总金额(万元)', value: 0, diff: 0 }
  ],
  projectStatus: {
    title: '',
    text: '',
    update: "",
    chartData: {
      labels: ["项目立项", "项目实施", "项目验收", "项目核算", "项目质保", "待归档", "已归档"],
      data: [0, 0, 0, 0, 0, 0, 0]
    }
  },
  pieData: {
    title: '',
    subtitle: '',
    diff: 0,
    update: "",
    data: [

    ]
  },
  // 生成图表需要的 labels 和 datasets
  lineData: {
    title: '月度新增项目统计',
    subtitle: '',
    diff: 0,
    update: "",
    labels: [],
    datasets: [
      {
        label: '新增项目数',
        data: [],
        borderColor: '#42b883',
        backgroundColor: '#42b883',
        fill: false,
      },
    ],
  },

  waitList: [],
  warrantyListD: [],
  overTime: [],
  implementListD: [],
  allProjectYear: [],
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  assistParams:{
    pageNum: 1,
    pageSize: 10,
  },
  warrantyQueryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  waitPayeeQueryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  overTimeQueryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  waitCompeleteQueryParams: {
    pageNum: 1,
    pageSize: 10,
  },

  yearParams: {
    pageNum: 1,
    pageSize: 10,
  },


});
//加载中状态
const loading = ref(true);
const assistList = ref([]);
//第一个板块的数据
const {warrantyQueryParams,waitPayeeQueryParams,overTimeQueryParams, waitCompeleteQueryParams,firstPanel, projectStatus, pieData, lineData, waitList,yearParams, warrantyListD, overTime, form, implementListD, allProjectYear, assistParams,queryParams } = toRefs(data);

//第一个板块加载中数据
const firstLoading = ref(true);
const total = ref(0);
const warrantyTotal = ref(0);
const waitPayeeTotal = ref(0);
const overTimeTotal = ref(0);
const waitCompeleteTotal = ref(0);

const warrantyCount = ref('')
  const waitPaymentCount = ref('')
  const overTimeCount = ref('')
  const waitComplete = ref('')


// 创建 ref 指向子组件
const chartCardRef = ref(null)
//动态获取卡片高度 设置给饼图
const cardHeight = ref('0px')
//获取当前年份
const currentYear = new Date().getFullYear()
//起始年份 从2024年开始
const startYear = 2024
// 年份数组：从 2024 到 currentYear + 1
const years = []
for (let year = startYear; year <= currentYear + 1; year++) {
  years.push(year)
}

// 类型循环数组
const types = ['primary', 'success', 'warning', 'danger']

// 默认选中当前年份
const selectedYear = ref(currentYear)

// 选择年份的方法
function getDataByYear(year) {
  selectedYear.value = year
  //1.获取第一个板块的内容 项目总金额 结算总金额 开票总金额 收款总金额
  getData(year, "1")
}

// 图标映射表
const cardMapping = {
  '项目总金额(万元)': {
    icon: { name: 'attach_money', color: 'text-white', background: 'dark' }
  },
  '结算总金额(万元)': {
    icon: { name: 'balance', color: 'text-white', background: 'info' }
  },
  '开票总金额(万元)': {
    icon: { name: 'receipt', color: 'text-white', background: 'primary' }
  },
  '收款总金额(万元)': {
    icon: { name: 'paid', color: 'text-white', background: 'success' }
  }
}

// 模拟后端返回的数据
const backendData = [
  { text: '项目总金额(万元)', value: 2568.89, diff: 22 },
  { text: '结算总金额(万元)', value: 1234.3, diff: 5 },
  { text: '开票总金额(万元)', value: 1635.22, diff: 3 },
  { text: '收款总金额(万元)', value: 1162.41, diff: -3 }
]

// 生成最终统计数据
const statisticsData = computed(() => {
  return firstPanel.value.map(item => ({
    title: {
      text: item.text,
      value: item.value
    },
    diff: item.diff,
    icon: cardMapping[item.text]?.icon || {
      name: 'help_outline',
      color: 'text-white',
      background: 'secondary'
    }
  }))
})

// 生成 detail 内容
const generateDetail = (diff) => {
  const sign = diff > 0 ? '+' : ''
  const colorClass = diff >= 0 ? 'text-success' : 'text-danger'
  return `较去年 <span class='text-sm font-weight-bolder ${colorClass}'>${sign}${diff}万元</span>`
}


// 生成 detail 内容
const generateDetailProjectStatus = (diff) => {
  const sign = diff > 0 ? '+' : ''
  const colorClass = diff >= 0 ? 'text-success' : 'text-danger'
  return `较去年 <span class='text-sm font-weight-bolder ${colorClass}'>${sign}${diff}</span>`
}

// 生成 detail 内容
const generateDetailPieData = (pieData) => {
  const sign = pieData.diff > 0 ? '+' : ''
  const colorClass = pieData.diff >= 0 ? 'text-success' : 'text-danger'
  return `逾期未收 <span class='text-sm font-weight-bolder ${colorClass}'>${sign}${pieData.diff}元</span>`
}

const assistTotal  = ref(0)

const queryYear = ref()
const queryType = ref()
function getData(year, type) {

  let param = {
    year: year,
    refresh: type
  }
  queryYear.value = year
  queryType.value = type
  //第一个板块的数据
  getFirstPanelByYear(param).then((response) => {
    console.log("第一个板块的数据", response);
    firstPanel.value = response.data;
  })


  //第二个板块的数据 柱状图
  getProjectStatus(param).then((response) => {
    console.log("第二个板块的数据 柱状图", response.data);
    projectStatus.value = response.data;
  })


  //第二个板块的数据 饼图
  getPieData(param).then((response) => {
    console.log("第二个板块的数据 饼图", response.data);
    pieData.value = response.data;
  })

  //第二个板块的数据 折线图
  getLineData(param).then((response) => {
    console.log("第二个板块的数据 折线图", response.data);
    lineData.value = response.data;
  })



  //第三个板块的数据 待收款项目
  // waitPayment(param).then((response) => {
  //   console.log("第三个板块的数据 待收款项目", response);
  //   waitList.value = response.data.projectList;
  //   waitPaymentCount.value =  "待收款项目(" +  response.data.count + ")"

    
  // })


  waitPayeeQueryParams.value = {
    ...waitPayeeQueryParams.value, // 已有的查询参数
    ...param // 新增或覆盖的查询参数
  };

  waitPayment(waitPayeeQueryParams.value).then((response) => {
    console.log("第三个板块的数据 待收款项目", response);
    waitList.value = response.data.tableDataInfo.rows;
    waitPayeeTotal.value = response.data.tableDataInfo.total;
    waitPaymentCount.value =  "待收款项目(" +  waitPayeeTotal.value + ")"
  })

  //第三个板块的数据 超期项目
  // overTimeList(param).then((response) => {
  //   console.log("第三个板块的数据 超期项目", response);
  //   overTime.value = response.data.projectList;
  //   overTimeCount.value = "超期项目(" + response.data.count + ")"
  // })

  overTimeList(param).then((response) => {
    console.log("第三个板块的数据 超期项目", response);
    overTime.value = response.data.tableDataInfo.rows;
    overTimeTotal.value = response.data.tableDataInfo.total;
    overTimeCount.value = "超期项目(" + overTimeTotal.value + ")"
  })

  //第三个板块的数据 待收质保金项目
  // getWarrantyList(param).then((response) => {
  //   console.log("第三个板块的数据 待收质保金项目", response);
  //   warrantyListD.value = response.data.warrantyList;
  //   warrantyCount.value =  "待收质保金项目(" + response.data.count + ")"
  //   console.log("warrantyCount",warrantyCount.value);
    
  //   open1(warrantyListD.value)
  // })

    // 合并查询参数
    warrantyQueryParams.value = {
    ...warrantyQueryParams.value, // 已有的查询参数
    ...param // 新增或覆盖的查询参数
  };
  getWarrantyList(warrantyQueryParams.value).then((response) => {
    console.log("第三个板块的数据 待收质保金项目", response);
    warrantyListD.value = response.data.tableDataInfo.rows;

    warrantyTotal.value = response.data.tableDataInfo.total;
    warrantyCount.value =  "待收质保金项目(" + warrantyTotal.value + ")"
    console.log("warrantyCount",warrantyCount.value);
    open1(warrantyListD.value)
  })



  //第三个板块的数据 超期项目
  getRank(param).then((response) => {
    console.log("排行榜", response);
    salesRank.value = response.data.dataViewList;
    profitRank.value = response.data.profitViewList
    profitRateRank.value = response.data.profitRateViewList;
  })

  //第三个板块的数据 待竣工项目
  getImplementDataView(param).then((response) => {
    implementListD.value = response.data.tableDataInfo.rows;
    waitCompeleteTotal.value = response.data.tableDataInfo.total;
    waitComplete.value =  "待竣工项目(" + waitCompeleteTotal.value + ")"
  })


  // 合并查询参数
  queryParams.value = {
    ...queryParams.value, // 已有的查询参数
    ...param // 新增或覆盖的查询参数
  };


console.log("yeeeeee",queryParams.value);

  //第三个板块的数据 年度项目汇总
  getAllProjectYear(queryParams.value).then((response) => {
    console.log("年度项目汇总", response);
    allProjectYear.value = response.data.rows;
    total.value = response.data.total;
  })

  


  let paramT = {
    projectType:'4'
  }
    // 合并查询参数
    assistParams.value = {
      ...assistParams.value,
    ...paramT // 新增或覆盖的查询参数
  };
  getAssistList(assistParams.value).then((response) => {
    console.log("配合项目", response.data);
    assistList.value = response.data.rows;
    assistTotal.value = response.data.total;
  });


}


function getYearProject() {
  //第三个板块的数据 年度项目汇总

  let paramT = {
    year:selectedYear.value
  }
    // 合并查询参数
    yearParams.value = {
      ...yearParams.value,
    ...paramT // 新增或覆盖的查询参数
  };

  getAllProjectYear(yearParams.value).then((response) => {
    console.log("年度项目汇总", response);
    allProjectYear.value = response.data.rows;
    total.value = response.data.total;
  })
}


function getWaitPayeeProject(){
  let param = {
    year: queryYear.value,
    refresh: queryType.value
  }
  waitPayeeQueryParams.value = {
    ...waitPayeeQueryParams.value, // 已有的查询参数
    ...param // 新增或覆盖的查询参数
  };

  waitPayment(waitPayeeQueryParams.value).then((response) => {
    console.log("第三个板块的数据 待收款项目", response);
    waitList.value = response.data.tableDataInfo.rows;
    waitPayeeTotal.value = response.data.tableDataInfo.total;
    waitPaymentCount.value =  "待收款项目(" +  waitPayeeTotal.value + ")"
  })
}

function getWaitCompleteProject(){
  let param = {
    year: queryYear.value,
    refresh: queryType.value
  }
  waitCompeleteQueryParams.value = {
    ...waitCompeleteQueryParams.value, // 已有的查询参数
    ...param // 新增或覆盖的查询参数
  };


  getImplementDataView(waitCompeleteQueryParams.value).then((response) => {
    console.log("待竣工项目", response);
    implementListD.value = response.data.tableDataInfo.rows;
    waitCompeleteTotal.value = response.data.tableDataInfo.total;
    waitComplete.value =  "待竣工项目(" + waitCompeleteTotal.value + ")"
  })
}

function getOverTotalProject(){
  let param = {
    year: queryYear.value,
    refresh: queryType.value
  }
  overTimeQueryParams.value = {
    ...overTimeQueryParams.value, // 已有的查询参数
    ...param // 新增或覆盖的查询参数
  };
  overTimeList(overTimeQueryParams.value ).then((response) => {
    console.log("第三个板块的数据 超期项目", response);
    overTime.value = response.data.tableDataInfo.rows;
    overTimeTotal.value = response.data.tableDataInfo.total;
    overTimeCount.value = "超期项目(" + overTimeTotal.value + ")"
  })

}


function getWarrantyProject() {
  let param = {
    year: queryYear.value,
    refresh: queryType.value
  }
  warrantyQueryParams.value = {
    ...warrantyQueryParams.value, // 已有的查询参数
    // ...param // 新增或覆盖的查询参数
  };
  //第三个板块的数据 待收质保金项目
  getWarrantyList(warrantyQueryParams.value).then((response) => {
    console.log("第三个板块的数据 待收质保金项目", response);
    warrantyListD.value = response.data.tableDataInfo.rows;
    warrantyTotal.value = response.data.tableDataInfo.total;
    warrantyCount.value =  "待收质保金项目(" + warrantyTotal.value + ")"
    console.log("warrantyCount",warrantyCount.value);
    open1(warrantyListD.value)
  })

}

const open1 = (datas) => {
  if (!datas || datas.length === 0) return;

  // 构建每个项目的截止日期信息
  const deadlineLines = datas
    .filter(item => item.warrantyRemaining > 0)
    .slice(0, 5) // 只取前五条数据
    .map(item => {
      const deadlineDate = new Date(item.endDate);
      const formattedDeadline = formatDate(deadlineDate); // 假设你已定义 formatDate 方法
      const days = item.warrantyRemaining;

      return `
        <div style="margin-top: 8px;">
          <span style="color: #626aef; font-weight: bold;">${item.projectName}</span><br>
          <span style="color: #666;">截止日期：</span>
          <span style="color: red;">${formattedDeadline}</span>&nbsp;&nbsp;
          <span style="color: #666;">剩余天数：</span>
          <span style="color: red;">${days} 天</span>
        </div>
      `;
    });

  // 拼接最终消息内容
  const notificationMessage = `
    <div style="margin-bottom: 10px; font-weight: bold; color: black;">
      以下项目已临近质保期，请注意查收质保金
    </div>
    ${deadlineLines.join('')}
  `;

  // 创建通知
  ElNotification({
    title: '通知',
    message: h('div', {
      style: {
        whiteSpace: 'normal',
        wordBreak: 'break-word',
        lineHeight: '1.5'
      },
      innerHTML: notificationMessage
    }),
    duration: 8000,
    customClass: 'my-custom-notification'
  });
};
function formatDate(date) {
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}
let resizeObserver = null

// 获取高度函数
const getCardHeight = () => {
  if (chartCardRef.value?.$el) {
    cardHeight.value = chartCardRef.value.$el.offsetHeight + 'px'
    console.log("cardHeight", cardHeight.value);

  }
}

async function handleView(row) {
  activeName.value = "first"
  isView.value = true
  getProjectInfo(row.projectNo)
  const _projectNo = row.projectNo || ids.value;
  await getProject(_projectNo).then((response) => {
    form.value = response.data;
    openView.value = true;
  });

}

function handles(row, types) {
  console.log("首页跳转", row);
  if (row.phaseId == "3") {//项目实施
    router.push({
      path: '/implement/projectImplement',
      query: {
        projectNo: row.projectNo,
        type: 'dataView',
      }
    });

  }
  else if (row.phaseId == "4") {//项目验收
    router.push({
      path: '/accept/projectAccept',
      query: {
        projectNo: row.projectNo,
        type: 'dataView',
      }
    });
  }
  else if (row.phaseId == "5") {//项目核算
    router.push({
      path: '/projectAccounting/accounting',
      query: {
        projectNo: row.projectNo,
        type: 'dataView',
      }
    });
  }
  else if (row.phaseId == "2") {//立项前期
    router.push({
      path: '/approve/projecPreMange',
      query: {
        projectNo: row.projectNo,
        type: 'dataView',
      }
    });
  }

  else if (row.phaseId == "1") {//项目立项
    router.push({
      path: '/project/projectManage',
      query: {
        projectNo: row.projectNo,
      }
    });
  }
  else if (row.phaseId == "6") {
    router.push({
      path: '/warranty/projectWarranty',
      query: {
        projectNo: row.projectNo,
      }
    });
  }
  else {
    proxy.$modal.msgError("暂无待处理数据");
  }
}


function handleWarranty(row) {
  router.push({
    path: '/warranty/projectWarranty',
    query: {
      projectNo: row.projectNo,
      type: 'dataView',
    }
  });
}

function getProjectInfo(projectNo) {
  console.log("projectNoprojectNo", projectNo);

  let params = {
    projectNo: projectNo
  }


  //参与人
  listParticipan(params).then((response) => {
    console.log("参与人员", response);
    personList.value = response.data
  });

  //附件
  listAttachment(params).then((response) => {
    attachmentList.value = response.data;
  });

  //付款信息
  listPay(params).then((response) => {
    payList.value = response.data;
  });

  //核算信息
  listAccounting(params).then((response) => {
    accountingList.value = response.data;
  });

  //质保信息
  listWarranty(params).then((response) => {
    warrantyList.value = response.data;
  });

  listImplement(params).then((response) => {
    implementList.value = response.data;
  });



}


// 假设这是从后端获取的数据
const salesRank = ref([
  {
    text: '冠军： - ¥ 0 万元',
    subText: '利润0 '
  },
  {
    text: '亚军 - ¥ 0 万元',
    subText: '利润0 '
  },
  {
    text: '季军 - ¥ 0 万元',
    subText: '利润0 '
  },

]);

const profitRank = ref([
  {
    text: '冠军： - ¥ 0 万元',
    subText: '利润0 '
  },
  {
    text: '亚军 - ¥ 0 万元',
    subText: '利润0 '
  },
  {
    text: '季军 - ¥ 0 万元',
    subText: '利润0 '
  },

]);


const profitRateRank = ref([
  {
    text: '冠军： - ¥ 0 万元',
    subText: '利润0 '
  },
  {
    text: '亚军 - ¥ 0 万元',
    subText: '利润0 '
  },
  {
    text: '季军 - ¥ 0 万元',
    subText: '利润0 '
  },

]);

// 根据排名显示不同的图标
const rankIcons = [
  { component: 'emoji_events', class: 'text-warning' },     // 第一名
  { component: 'military_tech', class: 'text-secondary' },  // 第二名
  { component: 'workspace_premium', class: 'text-danger' }, // 第三名
  { component: 'star', class: 'text-info' },                // 第四名
  { component: 'trending_up', class: 'text-success' }       // 第五名
];

// 获取对应排名的图标
const getRankIcon = (index) => {
  return rankIcons[index] || rankIcons[rankIcons.length - 1]; // 超出范围时默认最后一个图标
};
onMounted(() => {
  getData(currentYear, "1")
  getCardHeight()

  // 使用 ResizeObserver 监听卡片高度变化
  if (chartCardRef.value?.$el) {
    resizeObserver = new ResizeObserver(getCardHeight)
    resizeObserver.observe(chartCardRef.value.$el)
  }
})

onBeforeUnmount(() => {
  if (resizeObserver) {
    resizeObserver.disconnect()
  }
})
</script>
<style lang="scss" scoped>
.dashboard-editor-container {
  padding: 32px;
  background-color: rgb(240, 242, 245);
  position: relative;

  .github-corner {
    position: absolute;
    top: 0px;
    border: 0;
    right: 0;
  }

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 32px;
  }
}

@media (max-width:1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>


<style>
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.my-custom-notification {
  width: 400px;
}

.el-table .gray2-row {
  --el-table-tr-bg-color: #fab1bb;
  /* Element Plus 默认的浅灰背景色之一 */
}
</style>